package com.online.fund.util;

import java.net.InetAddress;
import java.util.Random;

/**
* 分布式高效有序ID生产黑科技(sequence)
* @author lry
*/
public class Sequence {
	
	private volatile static Sequence seqInstance;
	private static int counter = 0;
	private static final int ipRandomInt;
	private static final int jvmRandomInt;
	private static final int lastRandomInt;

	static {
		int IP;
		long JVM = System.currentTimeMillis();
		try {
			IP = toInt(InetAddress.getLocalHost().getAddress());
		} catch (Exception e) {
			IP = 0;
		}
		Random ipRandom = new Random(IP);
		Random jvmRandom = new Random(JVM);
		Random lastRandom = new Random();
		ipRandomInt = ipRandom.nextInt(800) + 100;
		jvmRandomInt = jvmRandom.nextInt(90) + 10;
		lastRandomInt = lastRandom.nextInt(10000);
	}
	
	private Sequence(){
	}

	protected int getCount() {
		synchronized (Sequence.class) {
			if (counter < 0)
				counter = 0;
			return counter++;
		}
	}
	
	private Long generate() {
		long millisecond = System.currentTimeMillis();
		int count = lastRandomInt + getCount();
		long id = ipRandomInt * 1000000000000000L + millisecond * 10000 + jvmRandomInt * 1000 + count;
		return id;
	}

	private static int toInt(byte[] bytes) {
		int result = 0;
		for (int i = 0; i < 4; i++) {
			result = (result << 8) - Byte.MIN_VALUE + bytes[i];
		}
		return result;
	}
	/**
	 * 获取一个默认的序列生成实例
	 * @return
	 */
	private static Sequence getInstance(){

		if (null == seqInstance) {
			synchronized (Sequence.class) {
				if (null == seqInstance) {
					seqInstance = new Sequence();
				}
			}
		}
		return seqInstance;
	}

	/**
	 * 获获取下一个ID
	 * @return
	 */
	public static long sequenceId(){
		return getInstance().generate();
	}
	public static void main(String[] args) {
		int i = 10;
		while(i>0){
			System.out.println(Sequence.sequenceId());
			i--;
		}
	}

}